@file:Suppress("DEPRECATION")

package com.et.util

import android.os.Environment
import com.et.logger.ELog
import com.et.logger.TAGS
import org.json.JSONObject
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

fun logUpload(uuid: String, json: JSONObject, callback: FtpCallbackListener) {
    Environment.getExternalStoragePublicDirectory("log").apply {
        if (exists()) {
            ELog.d(TAGS.launch, "logger:start select log files")
            val date = json.getString("date")
            val dateFolder = File(this, date)
            dateFolder.mkdir()
            if (dateFolder.exists()) {
                val logList = this.listFiles()
                if (logList != null && logList.isNotEmpty()) {
                    logList.forEach {
                        if (it.isFile) {
                            if (it.name.contains(date)) {
                                FileInputStream(it).channel.use { input ->
                                    FileOutputStream(
                                        File(dateFolder, it.name)
                                    ).channel.use { outPut ->
                                        outPut.transferFrom(input, 0, input.size())
                                    }
                                }
                            }
                        }
                    }
                    if (dateFolder.listFiles()?.isEmpty() != false) {
                        callback.onFinish(FtpUtil.Response(false, "当天日志为空"))
                        dateFolder.deleteFile()
                        return
                    }
                    val zipFile = File(this, "${uuid}_${date}.zip")
                    zipFolder(dateFolder.absolutePath, zipFile.absolutePath)
                    FtpUtil.getInstance().uploadFile(FtpUtil.Request().apply {
                        host = json.getString("host")
                        port = json.getString("port").toInt()
                        userName = json.getString("username")
                        password = json.getString("password")
                        remoteFolderPath = json.getString("remoteFolderPath")
                        fileName = zipFile.name
                        inputStream = FileInputStream(zipFile)
                    }).subscribe({
                        callback.onFinish(it)
                        dateFolder.deleteFile()
                        zipFile.deleteFile()
                    }, {
                        callback.onError(it)
                    })
                }
            }
        }
    }
}

interface FtpCallbackListener {
    fun onFinish(response: FtpUtil.Response)
    fun onError(e: Throwable)
}